/*
 * @Author: Robin
 * @Date: 2020/6/29 18:08
 * @LastEditors: Robin
 * @LastEditTime: 2021-09-02 11:59:18
 * @Description: 使用命令行工具进行图片压缩处理
 */
package main

import (
	"bytes"
	"flag"
	"fmt"
	"os"
	"os/exec"
	"time"
)

func main() {
	src := flag.String("src", "", "原始文件")
	target := flag.String("target", "thumb.jpg", "目标文件")
	size := flag.String("size", "400", "目标文件大小")
	quality := flag.String("quality", "85", "目标文件质量")
	flag.Parse()
	// file := "hd.jpg"
	// size := "400"
	buf := bytes.NewBuffer([]byte{})
	// GraphicsMagick
	cmd1 := exec.Command("gm", "convert", *src, "-quality", *quality, "-thumbnail", *size, *target)
	// ImageMagick
	cmd2 := exec.Command("convert", *src, "-quality", *quality, "-thumbnail", *size, *target)
	cmd1.Stderr = buf
	cmd2.Stderr = buf
	fmt.Println(time.Now()) // 计算耗时
	if err := cmd1.Run(); err != nil {
		fmt.Println(err)
		fmt.Println(buf.String()) // 输出错误详情
		return
	}
	fmt.Println(time.Now())
	os.Remove(*target)      // 删除文件，重新压缩
	fmt.Println(time.Now()) // 计算耗时
	if err := cmd2.Run(); err != nil {
		fmt.Println(err)
		fmt.Println(buf.String()) // 输出错误详情
		return
	}
	fmt.Println(time.Now())
}
